package logic

import (
	"context"
	"time"

	model "paper-pro/app/assistant/model/assistant"
	"paper-pro/app/assistant/rpc/internal/svc"
	"paper-pro/app/assistant/rpc/pb"
	"paper-pro/pkg/constants"
	delchattask "paper-pro/pkg/types"
	"paper-pro/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteAssistantLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeleteAssistantLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteAssistantLogic {
	return &DeleteAssistantLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DeleteAssistantLogic) DeleteAssistant(in *pb.DeleteAssistantReq) (*pb.DeleteAssistantResp, error) {
	_, err := l.svcCtx.RedisClient.Publish(constants.AssistantDeleteEvent, in.Id)
	if err != nil {
		return nil, errors.Wrapf(err, "DeleteAssistant failed: Id: %s, 发布删除消息失败", in.Id)
	}

	assistant, err := l.svcCtx.AssistantModel.Delete(l.ctx, in.Id, in.UserId)
	if err != nil && err != model.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"删除ID: %s Assistant失败，err: %v", in.Id, err)
	}
	if assistant == nil {
		return nil, errors.Wrapf(ErrAssistantNoExistsError, "DeleteAssistant ID:%s", in.Id)
	}

	taskPayload, err := delchattask.DelAssistantPayload(assistant.ID.Hex(), assistant.UserId)
	if err != nil {
		l.Errorf("DeleteAssistant Id: %s: delay delete chat dialog: Marshal task error: %v", assistant.ID.Hex(), err)
	}
	_, err = l.svcCtx.DqPusherClient.Delay(taskPayload, time.Minute*5)
	if err != nil {
		l.Errorf("DeleteAssistant Id: %s: delay delete chat dialog:push delay queue error: %v", assistant.ID.Hex(), err)
	}

	return &pb.DeleteAssistantResp{
		AssistantMeta: &pb.AssistantMeta{
			Id:        assistant.ID.Hex(),
			Name:      assistant.AssistantSetting.Name,
			LastUseAt: time.Now().Unix(),
		},
	}, nil
}
